import http.client
import json
import time

import pandas as pd
import openpyxl
import git
import os
from datetime import datetime
import xlsxwriter

###################### NORMAL RECORD ###########################
conn = http.client.HTTPSConnection("api.gitcode.com")
myToken = 'n1UG6VydsXys6-_W9137z2f2'
payload = ''
headers = {
    'Accept': 'application/json'
}
care_context = {
    'html_url': '',
    'title': '',
    'issue_state_detail': 'title',
    'issue_type_detail': 'title',
    'assignee': 'login',
    'priority': '',
    'number': ''
}

decode_context = {
    'html_url': '链接',
    'title': '标题',
    'issue_state_detail': '类型',
    'issue_type_detail': '优先级',
    'assignee': '责任人',
    'project': '关联版本'
}
decode_priority = {
    0: '未指定',
    1: '不重要',
    2: '次要',
    3: '主要',
    4: '致命'
}

GitCodeAllDatabase = ['CM', 'WR', 'DSS', 'DMS', 'CBB', 'docs', 'openGauss-server']
# GitCodeAllDatabase = ['WR']
issueALLType = ['待办的', '已完成', '修复中', '已答复']

csv_file = "GroupMember.xlsx"


###################### NORMAL RECORD ###########################


def GitPush(gitRep, commitMsg):
    repo = git.Repo(gitRep)

    if repo.is_dirty():
        repo.git.add(A=True)
        repo.index.commit(commitMsg)
        origin = repo.remote(name='origin')
        origin.push()
        print("Push successful")
    else:
        print("No changes to commit")


def GitPull(gitRep):
    repo = git.Repo(gitRep)
    origin = repo.remote(name='origin')
    origin.pull()
    print("Pull successful")


###############################################################

def GetAllDatabase(csvFile, issueType, careDash):
    groupDict, gitId2Name = GetStatusFromCSV(csvFile)
    dic = {'未指派': []}
    for database in GitCodeAllDatabase:
        GitAllIssueSpliteByDashBoard(groupDict, gitId2Name, issueType, careDash, database, dic)
    for key, value in dic.items():
        print('{name}.xlsx write begin'.format(name=key))
        df = pd.DataFrame(value)
        execelFileName = '{name}.xlsx'.format(name=key)
        workbook = xlsxwriter.Workbook(execelFileName)
        worksheet = workbook.add_worksheet()

        # 写入列名到 Excel 文件
        for col_num, value in enumerate(df.columns):
            worksheet.write(0, col_num, value)

        # 写入 DataFrame 中的数据到 Excel 文件
        for row_num, row_data in df.iterrows():
            for col_num, value in enumerate(row_data):
                worksheet.write(row_num + 1, col_num, value)  # +1 是因为第一行被用于列名

        # 保存并关闭 Excel 文件
        workbook.close()
        print('{name}.xlsx write down'.format(name=key))

    for key, value in dic.items():
        if key in careDash:
            caredDashBoardPickUpAndWrite(value, groupDict)
    return


def GitAllIssueSpliteByDashBoard(groupDict, gitId2Name, issueType, careDash, database, dic):
    for page in range(1, 10000):
        url = "/api/v5/repos/openGauss/{database}/issues?access_token={token}&page={page}&per_page=100".format(
            token=myToken, page=page, database=database)
        conn.request("GET", url, payload, headers)
        res = conn.getresponse()
        data = json.loads(res.read().decode("utf-8"))
        if not data:
            break
        for item in data:
            if item['issue_type'] != issueType:
                continue
            projectName = GetIssueSpecificForDashBoard(myToken, item['number'], database)
            temp = GetRecordFormJsonItem(item, gitId2Name, projectName)
            # 不关心无指派的问题单
            if temp is None:
                print(item['title'] + ' ' + item['html_url'])
                continue
            if projectName not in dic:
                dic[projectName] = []
            temp['仓库'] = database
            dic[projectName].append(temp)
            print(temp)
    print('{database} Parse down'.format(database=database))


# 直接根据版本数据进行筛选
def caredDashBoardPickUpAndWrite(data, groupDict):
    dict = {}
    for item in data:
        if item['类型'] not in issueALLType:
            continue
        group = 'noGroup'
        for key, value in groupDict.items():
            if item['责任人'] in value:
                group = key
                break
        if group not in dict:
            dict[group] = []
        dict[group].append(item)

    for key, kvalue in dict.items():
        print('{name}.xlsx group write begin'.format(name=key))
        df = pd.DataFrame(kvalue)
        execelFileName = '{name}.xlsx'.format(name=key)
        workbook = xlsxwriter.Workbook(execelFileName)
        worksheet = workbook.add_worksheet()

        # 写入列名到 Excel 文件
        for col_num, value in enumerate(df.columns):
            worksheet.write(0, col_num, value)

        # 写入 DataFrame 中的数据到 Excel 文件
        for row_num, row_data in df.iterrows():
            for col_num, value in enumerate(row_data):
                worksheet.write(row_num + 1, col_num, value)  # +1 是因为第一行被用于列名

        # 保存并关闭 Excel 文件
        workbook.close()
        print('{name}.xlsx group write down'.format(name=key))


def GetStatusFromCSV(csvFile):
    gitID2Name = {}
    groupDict = {}
    df = pd.read_excel(csvFile)
    for index, row in df.iterrows():
        groupName = row['属组']
        if groupName not in groupDict:
            groupDict[groupName] = []
        groupDict[groupName].append(row['中文名'])
        gitID2Name[row['GitCodeID']] = row['中文名']
    return groupDict, gitID2Name


def GetIssueStateByJson(item, gitId2Name, projectName):
    ret = {}
    for key, value in care_context.items():
        if value == '':
            ret[key] = item[key]
        else:
            ret[key] = item[key][value]
    ret['project'] = projectName
    return decodeResult(ret, gitId2Name)


def decodeResult(dic, gitId2Name):
    for key, value in decode_context.items():
        dic[value] = dic.pop(key)
    dic['优先级'] = dic.pop('priority')
    pri = dic['优先级']
    dic['优先级'] = decode_priority[pri]
    if dic['责任人'] != '':
        gitName = dic['责任人']
        dic['责任人'] = gitId2Name[gitName]
    return dic


def GetIssueSpecificForDashBoard(myToken, issueNum, database):
    ret = ''
    url = "/api/v5/repos/opengauss/{database}/issues/{issue}?access_token={token}".format(token=myToken,
                                                                                          issue=issueNum,
                                                                                          database=database)
    conn.request("GET", url, payload, headers)
    ress = conn.getresponse()
    data = json.loads(ress.read().decode("utf-8"))
    if 'kanban_values' in data:
        ret = data['kanban_values'][0]['name']
    else:
        ret = '未指派'
    return ret


def GetRecordFromGroup(csvFile):
    groupDict, gitId2Name = GetStatusFromCSV(csvFile)
    for key, value in groupDict.items():
        ret = workFunc(value, gitId2Name)
        df = pd.DataFrame(ret)
        df.to_excel('{name}.xlsx'.format(name=key), index=False, engine="openpyxl")


def GetRecordFormJsonItem(item, gitId2Name, projectName):
    ret = {}
    for key, value in care_context.items():
        if value == '':
            if key not in item:
                ret[key] = ''
            else:
                ret[key] = item[key]
        else:
            if key not in item:
                ret[key] = ''
            else:
                ret[key] = item[key][value]
    ret['project'] = projectName
    if ret['assignee'] not in gitId2Name:
        return None
    return decodeResult(ret, gitId2Name)


def GetUserIssues(userName, issueType_OpenOrClose, issueType, ret, gitId2Name):
    for page in range(1, 1000):
        url = "/api/v5/repos/openGauss/openGauss-server/issues?access_token={token}&page={page}&per_page=100&assignee={" \
              "userName}&state={issueType}".format(token=myToken, page=page, userName=userName,
                                                   issueType=issueType_OpenOrClose)
        conn.request("GET", url, payload, headers)
        res = conn.getresponse()
        data = json.loads(res.read().decode("utf-8"))
        if not data:
            return ret
        for item in data:
            if item['issue_type'] != issueType or item['issue_state'] not in issueALLType:
                continue
            projectName = GetIssueSpecificForDashBoard(myToken, item['number'])
            if projectName == '':
                print(item['title'])
                print(item['number'])
                continue
            temp = GetRecordFormJsonItem(item, gitId2Name, projectName)
            ret.append(temp)
    return


def workFunc(group, gitId2Name):
    ret = []
    for user in group:
        GetUserIssues(user, 'open', '缺陷', ret, gitId2Name)
    return ret


def main():
    while True:
        #GetAllDatabase(csv_file, '缺陷', ['openGauss 7.0.0-RC2 community'])
        #GetRecordFromGroup(csv_file)
        GitPush(os.path.abspath('.'), str(datetime.now()))
        time.sleep(600)


main()
